﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace WXB
{
    public class AnimDataHandler : XMLHandlerReg
    {
        public Dictionary<string, AnimData> AnimDataList;

        public AnimDataHandler(Dictionary<string, AnimData> dataList)
        {
            RegElementStart("AnimData", elementStart_AnimData);
            RegElementEnd("AnimData", elementEnd_AnimData);

            RegElementStart("ImageData", elementStart_ImageData);
            RegElementEnd("ImageData", elementEnd_ImageData);

            AnimDataList = dataList;
            if (AnimDataList == null)
                AnimDataList = new Dictionary<string, AnimData>();
        }

        AnimData CurrentData;
        void elementStart_AnimData(string element, XMLAttributes attributes)
        {
            CurrentData = new AnimData();
            CurrentData.name = attributes.getValue("name");
            CurrentData.speed = 1f /  attributes.getValueAsInteger("fps", 1);
            if (AnimDataList.ContainsKey(CurrentData.name))
            {
                Debug.LogError("AnimData name:" + CurrentData.name + " repeat!");
                return;
            }

            AnimDataList.Add(CurrentData.name, CurrentData);
        }

        void elementEnd_AnimData(string element)
        {
            CurrentData = null;
        }

        void elementStart_ImageData(string element, XMLAttributes attributes)
        {
            if (CurrentData == null)
            {
                Debug.LogError("CurrentData == null!");
                return;
            }

            string atlasName = attributes.getValue("atlas");
            UIAtlas atlas = ((GameObject)Resources.Load(atlasName, typeof(GameObject))).GetComponent<UIAtlas>();
            string name = attributes.getValue("spriteName");

            CurrentData.images.Add(new Image(atlas, name));
        }

        void elementEnd_ImageData(string element)
        {

        }
    }
}